package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.CarUsed;
import com.isunland.managesystem.entity.CarUsedParams;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.SimpleTreeListParams;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.ZTreeNode;
import com.isunland.managesystem.entity.ZTreeNodeListOriginal;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/6/6 10:39
 */
public class CarUsedNewDetailFragment extends BaseFragment {
  public static final String EXTRA_PARAMS =
      CarUsedNewDetailFragment.class.getSimpleName() + "EXTRA_PARAMS";
  protected static final String EXTRA_VALUE =
      CarUsedNewDetailFragment.class.getSimpleName() + "EXTRA_VALUE";

  private final int REQUEST_USESTARTDATA = 0;
  private final int REQUEST_PERSON = 1;
  private final int ADD = 2;
  private final int NEW = 3;
  private final int SUB = 4;
  private final int PUBLISH = 5;
  private static final int REQUEST_DELETE = 6;
  private static final int REQUEST_SUBMIT = 7;
  private static final int REQUSET_SAVE = 8;
  private static final int REQUSET_OTHER = 9;
  private static final int REQUEST_USEENDDATA = 10;
  private static final int REQUEST_DRIVER = 11;
  private static final int REQUEST_FILE = 12;
  private static final int REQUEST_UPLOAD = 13;
  private static final int REQUEST_CARSTATUS = 14;
  private static final int REQUEST_NUM_SOURCE = 15;

  @BindView(R.id.et_carUsedPerson) EditText etCarUsedPerson;
  @BindView(R.id.ib_carUsedPerson) ImageView ibCarUsedPerson;
  @BindView(R.id.tv_carUsedDept) TextView tvCarUsedDept;
  @BindView(R.id.et_carNum) EditText etCarNum;
  @BindView(R.id.tv_usedStartData) TextView tvUsedStartData;
  @BindView(R.id.tv_usedEndData) TextView tvUsedEndData;
  @BindView(R.id.et_carDriver) EditText etCarDriver;
  @BindView(R.id.et_startStopPlace) EditText etStartStopPlace;
  @BindView(R.id.et_startMileage) EditText etStartMileage;
  @BindView(R.id.et_endMileage) EditText etEndMileage;
  @BindView(R.id.tv_tripDistance) TextView tvTripDistance;
  @BindView(R.id.et_tolls) EditText etTolls;
  @BindView(R.id.et_oliConsumption) EditText etOliConsumption;
  @BindView(R.id.tv_carStatusName) TextView tvCarStatusName;
  @BindView(R.id.et_oliRemaining) EditText etOliRemaining;
  @BindView(R.id.tv_file) TextView tvFile;
  @BindView(R.id.et_carStatusDesc) EditText etCarStatusDesc;
  @BindView(R.id.et_causeRoute) EditText etCauseRoute;
  @BindView(R.id.tv_dataStatus) TextView tvDataStatus;
  @BindView(R.id.tv_regStaffName) TextView tvRegStaffName;
  @BindView(R.id.tv_regDate) TextView tvRegDate;
  @BindView(R.id.iv_file) ImageView ivFile;
  @BindView(R.id.ib_carNum) ImageView ibCarNum;
  @BindView(R.id.ib_carDriver) ImageView ibCarDriver;

  private CarUsed mContent;
  private int menuType;
  private String mId;

  private String mMainId;//主表id
  private String mMainName;//主表名

  private String driverId;
  private String carStatusCode;
  private String filePath;
  private CarUsedParams carParams;
  private String licensePlateId;
  private String carManCode;
  private String carDepartmentCode;
  private boolean carManSelect;
  private boolean carDriverSelect;
  private boolean carNumSelect;
  private CurrentUser mUser;

  public static CarUsedNewDetailFragment newInstance(CarUsed carUsed, BaseParams params) {
    CarUsedNewDetailFragment fragment = new CarUsedNewDetailFragment();
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_VALUE, carUsed);
    args.putSerializable(EXTRA_PARAMS, params);
    fragment.setArguments(args);
    return fragment;
  }

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initData();
  }

  public void initData() {
    setTitleCustom("车辆使用情况登记");
    mContent = (CarUsed) getArguments().getSerializable(EXTRA_VALUE);
    carParams = (CarUsedParams) getArguments().getSerializable(EXTRA_PARAMS);
    mUser = CurrentUser.newInstance(getActivity());
    carManSelect = false;
    carDriverSelect = false;
    carNumSelect = false;
    if (carParams != null) {
      mMainId = carParams.getMainId();
      mMainName = carParams.getMainNames();
    }
    if (mContent == null) {
      //添加: 保存,保存并提交
      menuType = ADD;
      mId = UUID.randomUUID().toString();
      driverId = mUser.getJobNumber();
      carStatusCode = "";
      carDepartmentCode = mUser.getDeptCode();
      carManCode = mUser.getJobNumber();
      filePath = "";
    }
    if (mContent != null) {
      mId = mContent.getId();
      if (carParams != null
          && carParams.getAdd()
          && carParams.getFrom() == CarUsedParams.CAR_APPLY) {
        //车辆申请跳转到车辆登记,添加界面
        mId = UUID.randomUUID().toString();
      }
      driverId = mContent.getDriverId();
      carStatusCode = mContent.getCarStatusCode();
      carDepartmentCode = mContent.getCarDepartmentCode();
      filePath = mContent.getFilePath();
      //详情
      if (DataStatus.NEW.equalsIgnoreCase(mContent.getDataStatus())) {
        //草稿:保存,提交,删除
        menuType = NEW;
      } else if (DataStatus.SUBMIT.equalsIgnoreCase(mContent.getDataStatus())) {
        //提交: 审核通过,退回
        menuType = SUB;
      } else if (DataStatus.NEWBACK.equalsIgnoreCase(mContent.getDataStatus())) {
        //终止: 保存,提交,删除
        menuType = NEW;
      } else {
        //已审核: 返回修改
        menuType = PUBLISH;
        if (carParams != null && CarUsedParams.CAR_APPLY == carParams.getFrom()) {
          //车辆申请进行登记时
          menuType = ADD;
        }
      }
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    switch (menuType) {
      //添加: 保存,保存并提交
      case ADD:
        inflater.inflate(R.menu.menu_save_submit, menu);
        menu.getItem(1).setTitle(R.string.submit);
        break;
      //草稿状态：保存、提交、删除
      case NEW:
        inflater.inflate(R.menu.menu_save_submit_delete, menu);
        menu.getItem(1).setTitle(R.string.submit);
        break;
      //提交状态：审核通过,返回修改
      case SUB:
        inflater.inflate(R.menu.menu_pass_stop, menu);
        break;
      //审核通过： 返回修改
      case PUBLISH:
        inflater.inflate(R.menu.menu_pass_stop, menu);
        menu.getItem(0).setVisible(false);
        break;
      default:
        break;
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();

        return true;
      case R.id.menu_item_save:
        //保存
        if (isCorrectInput()) {
          volleyPostSave(REQUSET_SAVE);
        }
        return true;
      case R.id.menu_item_submit:
        //保存并提交
        boolean isCorrectSubmit = isCorrectInput();
        if (isCorrectSubmit) {
          showDialog(BaseConfirmDialogFragment.newInstance(R.string.requisition_submit_hint), REQUEST_SUBMIT);
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        showDialog(BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm), REQUEST_DELETE);
        return true;
      case R.id.menu_item_pass:
        //审核通过
        volleyPostStatus(DataStatus.PUBLIS);
        return true;
      case R.id.menu_item_back:
        // 返回修改
        volleyPostStatus(DataStatus.NEWBACK);
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_new_car_used_detail, container, false);
    ButterKnife.bind(this, view);
    bindData();
    return view;
  }

  private void bindData() {
    if (mContent == null) {
      //添加
      etCarUsedPerson.setText(mUser.getRealName());
      tvCarUsedDept.setText(mUser.getDeptName());
      tvUsedStartData.setText(MyDateUtil.format(new Date(),MyDateUtil.TYPE_ALL));
      tvUsedEndData.setText(MyDateUtil.format(new Date(),MyDateUtil.TYPE_ALL));
      etCarDriver.setText(mUser.getRealName());
      tvTripDistance.setText("0");
      MyUtils.switchDataStutus(getActivity(), tvDataStatus, DataStatus.NEW);
      tvRegStaffName.setText(mUser.getRealName());
      tvRegDate.setText(MyDateUtil.parseDateToString(new Date()));
    } else {
      etCarNum.setText(mContent.getLicensePlateNumber());
      tvCarUsedDept.setText(mContent.getCarDepartmentName());
      etCarUsedPerson.setText(mContent.getCarManName());
      tvUsedStartData.setText(mContent.getUseStartDate());
      tvUsedEndData.setText(mContent.getUseEndDate());
      etCarDriver.setText(mContent.getDriverName());
      etStartStopPlace.setText(mContent.getStartStopPlace());
      etStartMileage.setText(mContent.getStartMileage());
      etEndMileage.setText(mContent.getEndMileage());
      tvTripDistance.setText(mContent.getTripDistance());
      etTolls.setText(mContent.getTolls());//通行费
      etOliConsumption.setText(mContent.getOliConsumption());//油耗
      tvCarStatusName.setText(mContent.getCarStatusName());//用车状况
      etOliRemaining.setText(mContent.getOliRemaining());//汽油剩余
      tvFile.setText(mContent.getFileName());//附件
      etCarStatusDesc.setText(mContent.getCarStatusDesc());//用车状况描述
      etCauseRoute.setText(mContent.getCauseRoute());//用车事由
      MyUtils.switchDataStutus(getActivity(), tvDataStatus, mContent.getDataStatus());
      tvRegStaffName.setText(mContent.getRegStaffName());
      tvRegDate.setText(mContent.getRegDate());
      if (DataStatus.PUBLIS.equalsIgnoreCase(mContent.getDataStatus())
          || DataStatus.SUBMIT.equalsIgnoreCase(mContent.getDataStatus())) {
        etCarUsedPerson.setEnabled(false);
        etCarNum.setEnabled(false);
        tvUsedStartData.setEnabled(false);
        tvUsedEndData.setEnabled(false);
        etCarDriver.setEnabled(false);
        etStartStopPlace.setEnabled(false);
        etStartMileage.setEnabled(false);
        etEndMileage.setEnabled(false);
        etTolls.setEnabled(false);//通行费
        etOliConsumption.setEnabled(false);//油耗
        tvCarStatusName.setEnabled(false);//用车状况
        etOliRemaining.setEnabled(false);//汽油剩余onc
        etCarStatusDesc.setEnabled(false);//用车状况描述
        etCauseRoute.setEnabled(false);//用车事由
        ibCarUsedPerson.setEnabled(false);
        ibCarNum.setEnabled(false);
        ibCarDriver.setEnabled(false);
        ivFile.setEnabled(false);
      }
    }
    etStartMileage.setOnFocusChangeListener(changeMileage());
    etEndMileage.setOnFocusChangeListener(changeMileage());
    etCarDriver.addTextChangedListener(textWatcher(CARDRIVER));
    etCarNum.addTextChangedListener(textWatcher(CARSOURCE));
    etCarUsedPerson.addTextChangedListener(textWatcher(CARMAN));
  }

  private View.OnFocusChangeListener changeMileage() {
    return new View.OnFocusChangeListener() {
      @Override public void onFocusChange(View view, boolean isFocus) {
        if (!isFocus) {
          if (!TextUtils.isEmpty(etStartMileage.getText().toString()) && !TextUtils.isEmpty(
              etEndMileage.getText().toString())) {
            int startMileage = Integer.parseInt(etStartMileage.getText().toString());
            int endMileage = Integer.parseInt(etEndMileage.getText().toString());
            if (endMileage < startMileage) {
              if (!TextUtils.isEmpty(etEndMileage.getText().toString())) {
                ToastUtil.show("结束公里数不能小于起步公里数!");
              }
              etEndMileage.setText("");
              tvTripDistance.setText("0");
            } else {
              int tripDistance = endMileage - startMileage;
              tvTripDistance.setText(String.valueOf(tripDistance));
            }
          }
        }
      }
    };
  }

  @OnClick({
      R.id.ib_carUsedPerson, R.id.tv_usedStartData, R.id.tv_usedEndData, R.id.ib_carDriver,
      R.id.tv_carStatusName, R.id.tv_file, R.id.iv_file, R.id.ib_carNum
  }) public void onClick(View view) {
    switch (view.getId()) {
      case R.id.tv_usedStartData:
        showDialog(BaseTimeDialogFragment.newInstance(
            mContent == null ? new Date() : MyDateUtil.parse(tvUsedStartData.getText().toString())),
            REQUEST_USESTARTDATA);
        break;
      case R.id.tv_usedEndData:
        showDialog(BaseTimeDialogFragment.newInstance(
            mContent == null ? new Date() : MyDateUtil.parse(tvUsedEndData.getText().toString())),
            REQUEST_USEENDDATA);
        break;
      case R.id.ib_carDriver:
        Intent driver = new Intent(getActivity(), SearchPersonActivity.class);
        driver.putExtra(SearchPersonListFragment.EXTRA_FROM, SearchPersonListFragment.VALUE_COMMON);
        startActivityForResult(driver, REQUEST_DRIVER);
        break;
      case R.id.ib_carUsedPerson:
        Intent usePerson = new Intent(getActivity(), SearchPersonActivity.class);
        usePerson.putExtra(SearchPersonListFragment.EXTRA_FROM,
            SearchPersonListFragment.VALUE_COMMON);
        startActivityForResult(usePerson, REQUEST_PERSON);
        break;
      case R.id.tv_carStatusName:
        //用车状态多选
        Intent carStatus = new Intent(getActivity(), CarStatusMultipleActivity.class);
        startActivityForResult(carStatus, REQUEST_CARSTATUS);
        break;
      case R.id.tv_file:
        //附件下载
        if (mContent != null && !TextUtils.isEmpty(mContent.getFilePath())) {
          showDialog(ExtraDownLoadDialogFragment.newInstance("", mContent.getFilePath()),
              REQUEST_FILE);
        }
        break;
      case R.id.iv_file:
        //附件上传
        //showDialog(ExtraUpLoadDialogFragment.newInstance(""), REQUEST_FILE);
        chooseFile(REQUEST_FILE);
        break;
      case R.id.ib_carNum:
        //资源
        volleyGetSource();
        break;
      default:
        break;
    }
  }

  private void chooseFile(int requestCode) {
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        requestCode);
  }

  /** 车辆资源 */
  private void volleyGetSource() {
    SimpleTreeListParams params = new SimpleTreeListParams();
    ZTreeNode item = new ZTreeNode();
    item.setName("资源目录");
    item.setId("0");
    params.setItem(item);
    params.setChildField("id");
    params.setParentField("pid");
    params.setTitleField("name");
    params.setTitle("请选择资源目录");
    params.setClassOriginal(ZTreeNodeListOriginal.class);
    params.setUrl(ApiConst.URL_CAR_APPLY_SOURCE);
    params.setSelectType(SimpleTreeListParams.ONLY_CHILD);//只能选择最底层节点
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode())
            .put("dictFlg", "resouceKindCode")
            .put("dataStatus", "publish"));
    BaseVolleyActivity.newInstance(this, ZTreeListActivity.class, params, REQUEST_NUM_SOURCE);
  }

  //删除
  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CAR_USED_DEL);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse(REQUSET_OTHER));
  }

  private void volleyPostSave(int requestCode) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CAR_USED_SAVE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    params.put("carManName", etCarUsedPerson.getText().toString());
    params.put("carManCode", carManCode);
    params.put("carDepartmentName", tvCarUsedDept.getText().toString());
    params.put("carDepartmentCode ", carDepartmentCode);//部门code
    params.put("licensePlateNumber", etCarNum.getText().toString());
    params.put("licensePlateId", licensePlateId);
    params.put("useStartDate", tvUsedStartData.getText().toString().trim());
    params.put("useEndDate", tvUsedEndData.getText().toString());
    params.put("driverId", driverId);
    params.put("driverName", etCarDriver.getText().toString());
    params.put("startStopPlace", etStartStopPlace.getText().toString());
    params.put("startMileage", etStartMileage.getText().toString());
    params.put("endMileage", etEndMileage.getText().toString());
    params.put("tripDistance", tvTripDistance.getText().toString());
    params.put("tolls", etTolls.getText().toString());
    params.put("oliConsumption", etOliConsumption.getText().toString());
    params.put("carStatusCode", carStatusCode);
    params.put("carStatusName", tvCarStatusName.getText().toString());
    params.put("oliRemaining", etOliRemaining.getText().toString());
    params.put("fileName", tvFile.getText().toString());
    params.put("filePath", filePath);
    params.put("carStatusDesc", etCarStatusDesc.getText().toString());
    params.put("causeRoute", etCauseRoute.getText().toString());
    if (carParams != null && carParams.getFrom() == CarUsedParams.LOCALE_WORK) {
      params.put("mainId", mMainId);
      params.put("mainName", mMainName);//作业任务
    } else if (carParams != null && carParams.getFrom() == CarUsedParams.CAR_APPLY) {
      params.put("applyId", mMainId);//车辆申请记录id
    } else {
      params.put("mainId", "");
      params.put("mainName", "");//作业任务
      params.put("applyId", "");//车辆申请记录id
    }
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse(requestCode));
  }

  /**
   * 改变数据状态: 提交,审核通过,退回
   */
  private void volleyPostStatus(String dataStatus) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CAR_USED_STATUS);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    params.put("dataStatus", dataStatus);
    if (DataStatus.PUBLIS.equalsIgnoreCase(dataStatus)) {
      params.put("checkStaffId", CurrentUser.newInstance(getActivity()).getJobNumber());
      params.put("checkStaffName", CurrentUser.newInstance(getActivity()).getRealName());
    }
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse(REQUSET_OTHER));
  }

  public VolleyResponse getResponse(final int requestCode) {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
        if (message.getResult() == null) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        if (message.getResult() != null && SuccessMessage.SUCCESS.equalsIgnoreCase(
            message.getResult())) {
          if (requestCode == REQUEST_SUBMIT) {
            //保存并提交
            volleyPostStatus(DataStatus.SUBMIT);
          } else {
            ToastUtil.show(R.string.success_operation);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        }
        if (message.getResult() != null && SuccessMessage.FAILURE.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(message.getMessage());
          //return;
        }
      }
    };
  }

  //判断必填项
  public boolean isCorrectInput() {
    String startData = tvUsedStartData.getText().toString().trim();
    String endData = tvUsedEndData.getText().toString().trim();
    if (TextUtils.isEmpty(etCarNum.getText().toString())
        || TextUtils.isEmpty(etCarUsedPerson.getText().toString())
        || TextUtils.isEmpty(tvUsedStartData.getText().toString())
        || TextUtils.isEmpty(tvUsedEndData.getText().toString())
        || TextUtils.isEmpty(etCarDriver.getText().toString())
        || TextUtils.isEmpty(etStartStopPlace.getText().toString())
        || TextUtils.isEmpty(etStartMileage.getText().toString())
        || TextUtils.isEmpty(etEndMileage.getText().toString())) {
      ToastUtil.show(R.string.notComplete);
      return false;
    }

    Date start = MyDateUtil.parse(startData);
    Date end = MyDateUtil.parse(endData);
    if (start == null || end == null) {
      ToastUtil.show("日期格式不正确");
      return false;
    }
    if (start.after(end)) {
      ToastUtil.show(R.string.startTimeBeforeEndTime);
      return false;
    }
    return true;
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_USESTARTDATA) {
      //使用开始时间
      Date acquireDate = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      String usedDate = MyDateUtil.dateToString(acquireDate, MyDateUtil.TYPE_ALL);
      tvUsedStartData.setText(usedDate);
    }
    if (requestCode == REQUEST_USEENDDATA) {
      //使用结束时间
      Date acquireDate = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      String usedDate = MyDateUtil.dateToString(acquireDate, MyDateUtil.TYPE_ALL);
      tvUsedEndData.setText(usedDate);
    }
    if (requestCode == REQUEST_PERSON) {
      //用车人
      CustomerDialog dialog =
          (CustomerDialog) data.getSerializableExtra(SearchPersonListFragment.EXTRA_VALUE);
      carManCode = dialog.getJobNo();
      carDepartmentCode = dialog.getMemberCode();//部门code
      carManSelect = true;
      etCarUsedPerson.setText(dialog.getName());
      tvCarUsedDept.setText(dialog.getDept());
    }
    if (requestCode == REQUEST_DRIVER) {
      //驾驶员
      CustomerDialog dialog =
          (CustomerDialog) data.getSerializableExtra(SearchPersonListFragment.EXTRA_VALUE);
      driverId = dialog.getJobNo();
      carDriverSelect = true;
      etCarDriver.setText(dialog.getName());
    }
    if (requestCode == REQUEST_CARSTATUS) {
      //用车状况
      String carStatusName = data.getStringExtra(CarStatusMultipleFragment.EXTRA_NAMES);
      carStatusCode = data.getStringExtra(CarStatusMultipleFragment.EXTRA_CODES);
      tvCarStatusName.setText(carStatusName);
    }
    if (requestCode == REQUEST_NUM_SOURCE) {
      //资源目录
      SimpleTreeListParams params =
          (SimpleTreeListParams) data.getSerializableExtra(BaseFragment.EXTRA_PARAMS);
      ZTreeNode item = ((ZTreeNode) params.getItem());
      licensePlateId = item.getId();
      carNumSelect = true;
      etCarNum.setText(item.getName());
    }
    if (requestCode == REQUEST_FILE) {
      //String result = data.getStringExtra(ExtraUpLoadDialogFragment.EXTRA_RESULT);
      //附件上传
      showDialog(
          FileUploadDialgFragment.newInstance(getFile(data), mId, "vehicle_usage_registration",
              false), REQUEST_UPLOAD);
    }
    if (requestCode == REQUEST_UPLOAD) {
      //附件上传成功
      filePath = data.getStringExtra(FileUploadDialgFragment.EXTRA_PATH);
      tvFile.setText(FileUtil.getFileNameByFilePath(filePath));
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUEST_SUBMIT) {
      volleyPostSave(REQUEST_SUBMIT);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  private String getFile(Intent data) {
    String path1 = FileUtil.getPath(getActivity(), data.getData());
    File mFile = null;
    if (path1 != null) {
      mFile = new File(path1);
    }
    if (null == mFile) {
      Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      return "";
    }
    return mFile.getAbsolutePath();
  }

  final int CARMAN = 0;
  final int CARDRIVER = 1;
  final int CARSOURCE = 2;

  protected TextWatcher textWatcher(final int type) {
    return new TextWatcher() {
      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        switch (type) {
          case CARMAN:
            if (!carManSelect) {
              carManCode = "";
              carManSelect = false;
            }
            break;
          case CARDRIVER:
            //如果是选择不监听文字变化
            if (!carDriverSelect) {
              driverId = "";
              carDriverSelect = false;
            }
            break;
          case CARSOURCE:
            if (!carNumSelect) {
              licensePlateId = "";
              carNumSelect = false;
            }
            break;
          default:
        }
      }

      @Override public void afterTextChanged(Editable s) {

      }
    };
  }
}
